<?php

namespace services\export;

use common\models\base\Project;
use common\models\clinic\UserTreatment;
use common\models\export\Log;
use common\models\marketing\SourceChannel;
use common\models\marketing\Tags;
use common\models\member\Member;
use services\baibai\ConfigService;
use Yii;
use common\components\Service;
use yii\db\Expression;

class LogService extends Service
{
    /**
     * 记录导出日志
     * @param $params
     * @return bool|int
     * @author chenyuebin
     */
    public function createLog($params)
    {
        $log = new Log();
        $log->project_id = $params['project_id'];
        $log->created_at = time();
        $log->handle = $params['handle'];
        $log->handle_start_time = time();
        $log->module_name = $params['mudle_name'];
        $log->project_short_name = $params['project_short_name'];
        if ($log->save()) {
            return $log->id;
        }

        return false;
    }

    /**
     * 更新导出链接
     * @param $params
     * @return bool
     * @author chenyuebin
     */
    public function updateLog($params)
    {
        $log = Log::findOne(['id' => $params['id']]);
        $log->status = $params['status'];
        $log->updated_at = time();
        $log->down_link = $params['down_link'];
        $log->handle_end_time = time();
        $log->success_num = $params['success_num'];
        $log->failed_num = $params['failed_num'];
        $log->remark = $params['remark'];

        if (!$log->save()) {
            return false;
        }

        return true;
    }

    /**
     * 导出excel字段匹配
     *
     * @param $mudles_name
     * @param $select
     * @return array
     * @author chenyuebin
     */
    public function exportFiledList($mudles_name, $select)
    {
        // 导出excel字段匹配
        $titleField = [];
        foreach (ConfigService::HEADER_LIST[$mudles_name] as $key => $value) {
            if (in_array($key, $select)) {
                $titleField[] = $value;
            }
        }

        return $titleField;
    }

    /**
     * 导出的excel  title
     *
     * @param $mudles_name
     * @param $select
     * @return array
     * @author chenyuebin
     */
    public function exportHeaderList($mudles_name, $select)
    {
        // 导出的excel  title
        $header = [];
        foreach (ConfigService::MUDEL_LIST_FIELD[$mudles_name] as $value) {
            if (in_array($value['id'], $select)) {
                $header[] = $value['name'];
            }
        }

        return $header;
    }

    /**
     * 获取要筛选的条件列表
     *
     * @param $conditions
     * @param $mudles_name
     * @return array
     * @author chenyuebin
     */
    public function conditionList($conditions, $mudles_name)
    {
        // 筛选条件
        $conditionArr['tags'] = [];
        $conditionArr['other'] = [];
        $conditionArr['condition'] = ['and'];
        foreach ($conditions as $value) {
            if (!$value['id']) {
                continue;
            }
            if ($value['id'] == ConfigService::RECENTLY_CLINIC_NUM ||
                $value['id'] == ConfigService::RECENTLY_SURPLUS_NUM
            ) {
                continue;
            }

            // 针对患者模块中关于治疗表的条件则忽略，留给逻辑处理
            if ($mudles_name == ConfigService::PATIENT_ID &&
                (
                    $value['id'] == ConfigService::CLINIC_PROJECT_NAME_ID ||
                    $value['id'] == ConfigService::TOTAL_NUM ||
                    $value['id'] == ConfigService::HELP_NUM ||
                    $value['id'] == ConfigService::RECENTLY_CLINIC_NUM ||
                    $value['id'] == ConfigService::RECENTLY_SURPLUS_NUM ||
                    $value['id'] == ConfigService::CLINIC_TOTAL_NUM ||
                    $value['id'] == ConfigService::SY_CLINIC_TOTAL_NUM
                )
            ) {
                continue;
            }

            if (in_array($value['id'], [
                ConfigService::KF_LAST_CALLBACK_ID,
                ConfigService::YZ_LAST_CALLBACK_ID,
                ConfigService::KF_NEXT_CALLBACK_ID,
                ConfigService::YZ_NEXT_CALLBACK_ID,
                ConfigService::LAST_REVISITING_ID,
                ConfigService::NEXT_REVISITING_ID,
                ConfigService::MONEY_TIME_ID,
                ConfigService::RECENTLY_CLINIC_ID
            ])) {// 针对所有时间字段处理
                if ($value['operator'] == '=') {
                    $temp1 = [
                        '>=',
                        ConfigService::FIELD_LIST[$mudles_name][$value['id']],
                        strtotime(date("Y-m-d 00:00:00", strtotime($value['start_time'])))
                    ];
                    $temp2 = [
                        '<=',
                        ConfigService::FIELD_LIST[$mudles_name][$value['id']],
                        strtotime(date("Y-m-d 23:59:59", strtotime($value['end_time'])))
                    ];
                    array_push($conditionArr['condition'], $temp1, $temp2);
                } else {
                    $temp1 = [
                        'or',
                        ['<', ConfigService::FIELD_LIST[$mudles_name][$value['id']], strtotime(date("Y-m-d 00:00:00", strtotime($value['start_time'])))],
                        ['>', ConfigService::FIELD_LIST[$mudles_name][$value['id']], strtotime(date("Y-m-d 23:59:59", strtotime($value['end_time'])))]
                    ];
                    array_push($conditionArr['condition'], $temp1);
                }
            } elseif ($value['id'] == ConfigService::TAGS_ID) {// 标签条件
                if ($value['id'] != ConfigService::GENDER_ID && !$value['value']) {
                    continue;
                }

                if ($value['id'] == ConfigService::GENDER_ID && $value['value'] < 0) {
                    continue;
                }
                $selectFeild = ConfigService::FIELD_LIST[$mudles_name][$value['id']];
                $tagsName = Tags::find()->select('tags_name')->where(['id' => $value['value']])->scalar();
                if ($value['operator'] == '=') {
                    $temp = [new Expression("FIND_IN_SET(:value, $selectFeild)", [":value" => $tagsName])];
                } else {
                    $temp = [new Expression("!FIND_IN_SET(:value, $selectFeild)", [":value" => $tagsName])];
                }
                array_push($conditionArr['tags'], $temp);
            } elseif ($value['id'] == ConfigService::KF_LAST_CALLBACK_USER_ID || $value['id'] == ConfigService::YZ_LAST_CALLBACK_USER_ID) {// 上次回访人
                $user_name = Member::find()->select('realname')->where(['id' => $value['value']])->scalar();
                $temp = [
                    $value['operator'],
                    ConfigService::FIELD_LIST[$mudles_name][$value['id']],
                    $user_name
                ];
                array_push($conditionArr['condition'], $temp);
            } else if ($value['id'] == ConfigService::TOTAL_HELP_NUM) {// 本次正常数量剩余 + 本次援助数量剩余
                $con1 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::TOTAL_NUM];
                $con2 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::HELP_NUM];
                $temp = [
                    'operator' => $value['operator'],
                    'condition' => [
                        'value1' => $con1,
                        'value2' => $con2
                    ],
                    'value' => $value['value']
                ];
                array_push($conditionArr['other'], $temp);
            }/* else if ($value['id'] == ConfigService::SY_CLINIC_TOTAL_NUM) {// 剩余治疗数量（总计:正常+援助）
                $con1 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::TOTAL_NUM];
                $con2 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::HELP_NUM];
                $temp = [
                    'operator' => $value['operator'],
                    'condition' => [
                        'value1' => $con1,
                        'value2' => $con2
                    ],
                    'value' => $value['value']
                ];
                array_push($conditionArr['other'], $temp);
            }*/ else if ($value['id'] == ConfigService::CLINIC_SURPLUS_NUM) {// 本次治疗/新增/退费 - 正常数量 + 本次治疗/新增/退费 - 援助数量
                $con1 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::RECENTLY_CLINIC_NUM];
                $con2 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::RECENTLY_SURPLUS_NUM];
                $temp1 = [
                    'operator' => $value['operator'],
                    'condition' => [
                        'value1' => $con1,
                        'value2' => $con2
                    ],
                    'value' => $value['value']
                ];

                $temp2 = [
                    '=',
                    'type',
                    $mudles_name == ConfigService::TREATMENT_ID ? UserTreatment::TYPE_REDUCE : UserTreatment::TYPE_TREAT
                ];
                array_push($conditionArr['condition'], $temp2);
                array_push($conditionArr['other'], $temp1);
            } else if ($value['id'] == ConfigService::CLINIC_TOTAL_NUM) {// 治疗数量（总计:正常+援助）
                $con1 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::RECENTLY_CLINIC_NUM];
                $con2 = ConfigService::FIELD_LIST[$mudles_name][ConfigService::RECENTLY_SURPLUS_NUM];
                $temp1 = [
                    'operator' => $value['operator'],
                    'condition' => [
                        'value1' => $con1,
                        'value2' => $con2
                    ],
                    'value' => $value['value']
                ];

                $temp2 = [
                    '=',
                    'type',
                    $mudles_name == ConfigService::TREATMENT_ID ? UserTreatment::TYPE_REDUCE : UserTreatment::TYPE_TREAT
                ];
                array_push($conditionArr['condition'], $temp2);
                array_push($conditionArr['other'], $temp1);
                //本次治疗/新增/退费 - 正常数量 || 本次治疗/新增/退费 - 援助数量
            } /*else if ($value['id'] == ConfigService::RECENTLY_SURPLUS_NUM || $value['id'] == ConfigService::RECENTLY_CLINIC_NUM) {
                $temp1 = [
                    $value['operator'],
                    ConfigService::FIELD_LIST[$mudles_name][$value['id']],
                    $value['value']
                ];
                $temp2 = [
                    '=',
                    'type',
                    $mudles_name == ConfigService::TREATMENT_ID ? UserTreatment::TYPE_REDUCE : UserTreatment::TYPE_TREAT
                ];
                array_push($conditionArr['condition'], $temp1, $temp2);
            } */ else {
                if ($value['id'] != ConfigService::GENDER_ID && !$value['value']) {
                    continue;
                }

                if ($value['id'] == ConfigService::GENDER_ID && $value['value'] < 0) {
                    continue;
                }
                if (($mudles_name == ConfigService::MEDICAL_ID || $mudles_name == ConfigService::PATIENT_ID || $mudles_name == ConfigService::CALLBACK_ID) && $value['id'] == ConfigService::SOURCE_CHANNEL_ID) {// 针对渠道处理
                    $source_id_arr = SourceChannel::find()->select('id')->where(['or', ['pid' => $value['value']], ['id' => $value['value']]])->column();
                    if ($value['operator'] == '=') {
                        $operator = 'in';
                    } else {
                        $operator = 'not in';
                    }
                    $temp = [
                        $operator,
                        ConfigService::FIELD_LIST[$mudles_name][$value['id']],
                        $source_id_arr
                    ];
                    array_push($conditionArr['condition'], $temp);
                } else {
                    $temp = [
                        $value['operator'],
                        ConfigService::FIELD_LIST[$mudles_name][$value['id']],
                        $value['value']
                    ];
                    array_push($conditionArr['condition'], $temp);
                }
            }
        }

        return $conditionArr;
    }

    /**
     * 获取要查询的字段
     *
     * @param $select
     * @param $mudles_name
     * @return array
     * @author chenyuebin
     */
    public function selectList($select, $mudles_name)
    {
        // 查询的字段
        $selectArr = [];
        $fieldArr = [];
        foreach ($select as $value) {
            $fieldArr[] = $value;
            if ($mudles_name == ConfigService::PATIENT_ID &&
                (
                    $value == ConfigService::CLINIC_PROJECT_NAME_ID ||
                    $value == ConfigService::TOTAL_NUM ||
                    $value == ConfigService::HELP_NUM ||
                    $value == ConfigService::RECENTLY_CLINIC_NUM ||
                    $value == ConfigService::RECENTLY_SURPLUS_NUM ||
                    $value == ConfigService::CLINIC_TOTAL_NUM ||
                    $value == ConfigService::SY_CLINIC_TOTAL_NUM
                )
            ) {
                continue;
            } else {
                $selectArr[] = ConfigService::MUDEL_LIST_NAME[$mudles_name][$value];
            }
        }

        if (in_array(ConfigService::PATIENT_DISEASES_ID, $fieldArr)) {
            if ($mudles_name == ConfigService::PATIENT_ID || $mudles_name == ConfigService::MEDICAL_ID) {
                array_push($selectArr, 'a.patient_diseases_child_id');
            }
        }

        return $selectArr;
    }

    /**
     * 生成文件名称和存储路径
     *
     * @param $mudles_name
     * @param $handle
     * @param $project_id
     * @return array
     * @author chenyuebin
     */
    public function nameAndPAth($mudles_name, $handle, $project_id)
    {
        // 文件名称
        $preName = '';
        foreach (ConfigService::MUDLE_LIST as $value) {
            if ($value['id'] == $mudles_name) {
                $preName = $value['name'];
            }
        }

        $fileName = '[' . $preName . '数据]' . $handle . '__' . date("YmdHis") . '.xlsx';

        // 文件存储路径
        $project_sx = Project::find()->select(['name_sx'])->where(['id' => $project_id])->scalar();
        // 判断文件夹是否存在
        $path = Yii::$app->params['export_save_dir'] . $project_sx;
        if (!file_exists($path)){
            mkdir($path);
        }
        $savePath = Yii::$app->params['export_save_dir'] . $project_sx . '/' . $fileName;

        return [
            'fileName' => $fileName,
            'savePath' => $savePath,
            'preName' => $preName,
            'project_sx' => $project_sx
        ];
    }

    /**
     * 导出日志
     *
     * @param $project_id
     * @param $page
     * @param $pageSize
     * @return array
     * @author chenyuebin
     */
    public function exportLog($project_id, $page, $pageSize)
    {
        $query = Log::find()
            ->select(['id', 'handle', 'handle_start_time', 'handle_end_time', 'status', 'module_name', 'success_num', 'failed_num', 'project_short_name', 'down_link'])
            ->where(['project_id' => $project_id]);
        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query->orderBy('id desc')->asArray()->all();

        foreach ($list as $key => $value) {
            if (isset($value['handle_start_time']) && $value['handle_start_time']) {
                $list[$key]['handle_start_time'] = date("Y-m-d H:i:s", $value['handle_start_time']);
            }
            if (isset($value['handle_end_time']) && $value['handle_end_time']) {
                $list[$key]['handle_end_time'] = date("Y-m-d H:i:s", $value['handle_end_time']);
            }
            if (isset($value['down_link']) && isset($value['status']) && $value['status'] == Log::STATUS_SUCCESS) {
                $list[$key]['down_link'] = Yii::$app->params['download_url'] . '/' . $value['project_short_name'] . '/' . $value['down_link'];
            }
            if (isset($value['status'])) {
                $list[$key]['status_name'] = Log::STATUS_LIST[$value['status']];
            }
        }

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }
}